﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace blackhouse.Web {

	/// <summary>
	/// Dodaje obsługę automatycznej obsługi adresów url do mapowań plików.
	/// </summary>
	public class DynamicImageModule : IHttpModule {

		private static Dictionary<string, string> relations;
		private Dictionary<string, string> Relations {
			get {
				if (relations == null) {
					Dictionary<string, string> d = new Dictionary<string, string>();
					d.Add("dbdi", "DbDynamicImage");
					d.Add("fbdi", "DynamicImageFileBased");
					relations = d;
				}
				return relations;
			}
		}

		public void Dispose() { }

		public void Init(HttpApplication context) {
			context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
		}

		void context_AuthorizeRequest(object sender, EventArgs e) {
			string url = HttpContext.Current.Request.RawUrl;
			foreach (KeyValuePair<string, string> item in this.Relations) {
				if (url.Contains(item.Key + "/")) {
					this.Rewrite(item, url);
					break;
				}
			}
		}

		private void Rewrite(KeyValuePair<string, string> rewritePath, string url) {
			Regex r = new Regex(rewritePath.Key + @"/(.*)/(\d*)x(\d*)/(.*)");
			Match m = r.Match(url);
			if (m.Success) {
				string newUrl = "/" + rewritePath.Value + ".ashx?configuration=" + m.Groups[1].Value + "&width=" + m.Groups[2].Value + "&height=" + m.Groups[3].Value + "&file=" + m.Groups[4].Value;
				HttpContext.Current.RewritePath(newUrl);
			}
		}

	}
}